package com.hardson.toolkit.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.ArrayList;
import java.util.List;

/**
 * Json工具类，引用的json依赖可能为：fastJson,...
 *
 * @author hardson
 * @date 2023/8/30 上午11:06
 */
public class JsonUtil {

    /**
     * 使用FastJson进行深拷贝
     *
     * @param t 原对象
     * @return T 复制的对象
     * @author hardson
     * @date 2023/8/30 上午11:08
     */
    @SuppressWarnings("unchecked")
    public static <T> T deepClone(T t) {
        if (t instanceof List) {
            List<?> oriList = (List<?>) t;
            List<Object> newList = new ArrayList<>(oriList.size());
            for (Object obj : oriList) {
                Object clone = deepClone(obj);
                newList.add(clone);
            }
            return (T) newList;
        }
        String json = JSON.toJSONString(t, SerializerFeature.WriteClassName);
        return (T) JSON.parseObject(json, t.getClass());
    }
}
